import 'package:app/components/ColorCircle.dart';
import 'package:app/components/DynamicShapeBorderContainer.dart';
import 'package:app/components/TimeBox.dart';
import 'package:app/components/TimeView.dart';
import 'package:app/enum/CustomColors.dart';
import 'package:app/icons/icons.dart';
import 'package:app/model/app_config.dart';
import 'package:app/model/model.dart';
import 'package:app/router/router.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';

// 响应式颜色项
class _ItemColor {
  final Rx<Color> color;
  final Rx<bool> showBorder;
  _ItemColor({required Color c, bool r = false})
    : color = c.obs,
      showBorder = r.obs;

  void updateShowBorder(bool show) {
    showBorder.value = show;
  }
}

class UpdateColor extends StatefulWidget with RouterBridge<ChildrenEvent> {
  const UpdateColor({super.key});
  @override
  State<UpdateColor> createState() => _UpdateColorState();
}

class _UpdateColorState extends State<UpdateColor> {
  static const name = "某天";
  final Map<String, dynamic> _dartMap = {
    "childrenId": "",
    "name": name,
    "parentId": "1",
    "targetTimestamp": DateTime.now().millisecondsSinceEpoch,
    "isprecise": false,
    "whetherToTop": false,
    "eventColor": StaticAppConfig.defaultEventColor,
  };

  // 确保 event 是响应式对象
  late final Rx<ChildrenEvent> event;
  var _isInitialized = false;

  // 响应式颜色列表（Rx<_ItemColor>）
  final List<Rx<_ItemColor>> _colors = [];

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    if (!_isInitialized) {
      final args = widget.argumentsOf(context);
      if (args != null) {
        event = args.obs;
        if (args.name.isEmpty) {
          event.value.name.value = name;
        }
      } else {
        event = ChildrenEvent.fromJson(_dartMap).obs;
      }

      // 初始化默认颜色项
      _colors.add(
        _ItemColor(
          c: StaticAppConfig.defaultEventColor,
          r: event.value.eventColor.value == StaticAppConfig.defaultEventColor,
        ).obs,
      );

      // 初始化自定义颜色项
      var customColors = CustomColors.toList();
      for (var color in customColors) {
        _colors.add(
          _ItemColor(
            c: color.toColor,
            r: event.value.eventColor.value == color.toColor,
          ).obs,
        );
      }

      _isInitialized = true;
    }
  }

  void save() {
    Navigator.maybePop(context, event.value.eventColor.value);
  }

  void setColor(int index) {
    // 更新选中颜色
    event.value.eventColor.value = _colors[index].value.color.value;

    // 更新所有颜色项的边框状态
    for (var i = 0; i < _colors.length; i++) {
      _colors[i].value.updateShowBorder(
        event.value.eventColor.value == _colors[i].value.color.value,
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: TDNavBar(
        height: 48,
        title: "选择事件颜色",
        titleColor: Colors.white,
        centerTitle: false,
        backgroundColor: StaticAppConfig.appBarColor,
        titleFontWeight: FontWeight.w600,
        useDefaultBack: false,
        screenAdaptation: true,
        leftBarItems: [
          TDNavBarItem(
            icon: Icons.chevron_left,
            iconColor: Colors.white,
            action: () {
              Navigator.maybePop(context);
            },
          ),
        ],
      ),
      body: SizedBox.expand(
        child: Container(
          decoration: BoxDecoration(color: Color(0xFFCCCCCC)),
          child: Column(
            children: [
              Container(
                alignment: Alignment.center,
                padding: EdgeInsets.symmetric(vertical: 10, horizontal: 35),
                child: Column(
                  children: [
                    Obx(() {
                      return TimeView(childrenEvent: event.value,disableTap: true);
                    }),
                    SizedBox(height: 5),
                    Obx(
                      () => TimeBox(
                        name: event.value.name.value,
                        targetTimestamp: event.value.targetTimestamp.value,
                        color: event.value.eventColor.value,
                      ),
                    ),
                  ],
                ),
              ),

              // 颜色选择区域
              Container(
                height: 220,
                color: Colors.white,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(
                      padding: EdgeInsets.only(top: 15, left: 10),
                      child: Row(
                        children: [
                          Icon(TDIcons.color_invert),
                          const SizedBox(width: 5),
                          Text("选择更多事件颜色", style: TextStyle(fontSize: 18)),
                        ],
                      ),
                    ),
                    SizedBox(height: 20),
                    Expanded(
                      child: GridView.builder(
                        scrollDirection: Axis.horizontal,
                        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                          crossAxisCount: 2,
                          mainAxisSpacing: 20,
                          crossAxisSpacing: 20,
                          childAspectRatio: 1,
                        ),
                        itemCount: _colors.length,
                        itemBuilder: (context, index) {
                          return GestureDetector(
                            onTap: () {
                              setColor(index);
                            },
                            child: Obx(() {
                              final item = _colors[index].value;
                              return DynamicShapeBorderContainer(
                                width: 50,
                                height: 50,
                                showBorder: item.showBorder.value,
                                child: LayoutBuilder(
                                  builder: (_, __) {
                                    if (item.color.value ==
                                        StaticAppConfig.defaultEventColor) {
                                      return Icon(AppIcons.jinzhi);
                                    }
                                    return ColorCircle(color: item.color.value);
                                  },
                                ),
                              );
                            }),
                          );
                        },
                      ),
                    ),
                    SizedBox(height: 20),
                  ],
                ),
              ),
              // 保存按钮
              Container(
                padding: EdgeInsets.only(top: 15),
                child: TDButton(
                  text: '保存',
                  size: TDButtonSize.large,
                  type: TDButtonType.fill,
                  shape: TDButtonShape.round,
                  theme: TDButtonTheme.primary,
                  isBlock: true,
                  onTap: save,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
